﻿using System;
using System.Collections.Generic;
using System.Text;
//new
using System.Security.Cryptography;
using System.Globalization;

namespace JRCore.protocol
{
    /// <summary>
    /// 密钥
    /// </summary>
    public class SecretKey
    {
        /// <summary>
        /// 生成密钥
        /// </summary>
        /// <param name="ip">ip地址</param>
        /// <returns>密钥</returns>
        public static string GetKey(string ip)
        {
            string ans = "";
            try
            {
                if ((ip != null) && (ip != ""))
                {
                    string md5in = GetNewMC(ip);
                    ans = getMd5Hash(md5in);
                }
            }
            catch { ans = ""; }
            return ans;
        }

        private static string GetNewMC(string oldMC)
        {
            string newMC = "";
            for (int i = 0; i < oldMC.Length; i++)
            {
                newMC += Convert.ToChar(oldMC[i] * 2 + 3).ToString();
            }
            return newMC;
        }

        private static string getMd5Hash(string input)
        {
            // Create a new instance of the MD5CryptoServiceProvider object.
            MD5 md5Hasher = MD5.Create();

            // Convert the input string to a byte array and compute the hash.
            byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));

            // Create a new Stringbuilder to collect the bytes
            // and create a string.
            StringBuilder sBuilder = new StringBuilder();

            // Loop through each byte of the hashed data 
            // and format each one as a hexadecimal string.
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }

            string ans = sBuilder.ToString();
            ans = ans.Insert(24, "-");
            ans = ans.Insert(16, "-");
            ans = ans.Insert(8, "-");
            // Return the hexadecimal string.
            return ans;
        }
    }

}
